// ============================================================================
// Config 实体定义
// ============================================================================

import {
  Entity,
  PrimaryColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
  BeforeInsert
} from 'typeorm'
import { JsonTransformer } from '../transformers/json.transformer'
import { v4 as uuidv4 } from 'uuid'

/**
 * 配置实体
 */
@Entity('config')
@Index(['key'], { unique: true })
@Index(['isSystem'])
export class Config {
  @PrimaryColumn({ type: 'varchar' })
  id: string

  @Column({ type: 'varchar', unique: true })
  key: string

  @Column({ 
    type: 'text',
    transformer: new JsonTransformer()
  })
  value: any

  @Column({ type: 'text', nullable: true })
  description?: string

  @Column({ name: 'is_system', type: 'boolean', default: false })
  isSystem: boolean

  @CreateDateColumn({ name: 'created_at' })
  createdAt: Date

  @UpdateDateColumn({ name: 'updated_at' })
  updatedAt: Date

  @BeforeInsert()
  generateId() {
    if (!this.id) {
      this.id = uuidv4()
    }
  }

  /**
   * 检查是否为系统配置
   */
  isSystemConfig(): boolean {
    return this.isSystem
  }

  /**
   * 更新配置值
   */
  updateValue(value: any, description?: string): void {
    this.value = value
    if (description !== undefined) {
      this.description = description
    }
  }

  /**
   * 获取字符串值
   */
  getStringValue(): string {
    if (typeof this.value === 'string') {
      return this.value
    }
    return JSON.stringify(this.value)
  }

  /**
   * 获取数字值
   */
  getNumberValue(): number {
    if (typeof this.value === 'number') {
      return this.value
    }
    const num = Number(this.value)
    return isNaN(num) ? 0 : num
  }

  /**
   * 获取布尔值
   */
  getBooleanValue(): boolean {
    if (typeof this.value === 'boolean') {
      return this.value
    }
    if (typeof this.value === 'string') {
      return this.value.toLowerCase() === 'true'
    }
    return Boolean(this.value)
  }

  /**
   * 获取对象值
   */
  getObjectValue(): any {
    if (typeof this.value === 'object') {
      return this.value
    }
    try {
      return JSON.parse(this.value)
    } catch {
      return {}
    }
  }

  /**
   * 创建系统配置
   */
  static createSystemConfig(key: string, value: any, description?: string): Config {
    const config = new Config()
    config.key = key
    config.value = value
    config.description = description
    config.isSystem = true
    return config
  }

  /**
   * 创建用户配置
   */
  static createUserConfig(key: string, value: any, description?: string): Config {
    const config = new Config()
    config.key = key
    config.value = value
    config.description = description
    config.isSystem = false
    return config
  }

  /**
   * 转换为配置格式（向后兼容）
   */
  toConfigFormat() {
    return {
      id: this.id,
      key: this.key,
      value: this.value,
      description: this.description,
      isSystem: this.isSystem,
      createdAt: this.createdAt,
      updatedAt: this.updatedAt
    }
  }

  /**
   * 从配置数据创建配置实体
   */
  static fromConfigData(data: any): Config {
    const config = new Config()
    config.id = data.id || uuidv4()
    config.key = data.key
    config.value = data.value
    config.description = data.description
    config.isSystem = data.isSystem || false
    return config
  }
}
